<template>
  <view class="wrap">
    <view class="detail_top" @click="editRecord">
      <image class="avatar" :src="turtleMes.turtle_url" mode="aspectFill" />
      <view class="top_right">
        <view class="right_box">
          <view class="box_left">名字 : </view>
          <view class="box_right">{{ turtleMes.turtle_name }}</view>
        </view>
        <view class="right_box">
          <view class="box_left">品种 : </view>
          <view class="box_right">{{ turtleMes.turtle_varieties }}</view>
        </view>
        <view class="right_box">
          <view class="box_left">龟龄 : </view>
          <view class="box_right">{{ getTurtleYear(turtleMes.turtle_age) }}</view>
        </view>
        <view class="right_box">
          <view class="box_left">记录次数 : </view>
          <view class="box_right">{{ recordList.length }}</view>
        </view>
      </view>
    </view>
    <view class="detail_content" v-if="overLoad">
      <view class="record_list">
        <div class="record_box no_record" v-if="recordList.length <= 0">
          <view class="record_item">
            <view class="data_title">开始记录吧 ~</view>
          </view>
        </div>
        <div
          class="record_box"
          v-for="(item, index) in recordList"
          :key="item._id"
        >
          <l-swipeAction
            :data="item"
            :options="options"
            @clickItem="clickItem"
            :key="index"
          >
            <view class="record_item" @click="toRecordDetail(item._id)">
              <view class="data_tag" :style="'background:'+typeColors[item.record.type]" v-text="typeOptions[item.record.type]"></view>
              <view class="data_container" v-text="item.record.text_container"></view>
              <view class="data_mes" v-text="item.record.time"></view>
            </view>
          </l-swipeAction>
        </div>
      </view>
    </view>
    <view class="add_record" @click="toAddRecord">
      <image
        class="add_record_img"
        src="../../static/record/add_record.png"
        mode=""
      />
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { reactive } from 'vue';
import { authRequest } from '@/utils/authRequest.js';
import { getDate } from '@/utils/date.js'

// 响应式数据
const theId = ref('');
const turtleMes = ref({});
const recordList = ref([]);
const overLoad = ref(false);
const typeOptions = ref(['喂食', '换水', '记录', '其他']);
const typeColors = ref(['#FF5733', '#3d836d', '#4f63c3', '#F1C40F'])

const nowTime = ref(getDate({ format: true }))
// 滑动操作配置
const options = reactive([
  {
    name: '删除',
    width: 100,
    background: '#f35050',
    color: '#fff',
  },
  {
    name: '置顶',
    width: 100,
    background: '#0fa0f9',
    color: '#fff',
  },
]);

// 获取乌龟信息
const getTurtle = async () => {
  try {
    const res = await authRequest('findTurtle', { _id: theId.value });
    
    if (res.result.code === 200) {
      turtleMes.value = res.result.data.data[0];
    }
  } catch (e) {
    console.error('获取乌龟信息失败:', e);
    uni.showToast({ title: '获取乌龟信息失败', icon: 'none' });
  }
};

// 获取记录列表
const getRecordList = async () => {
  try {
    const res = await authRequest('findRecordList', { _id: theId.value });
    
    if (res.result.code === 200) {
      console.log(res.result.data.data);
      recordList.value = res.result.data.data.map((item) => ({
        ...item,
        show: false,
      }));
      overLoad.value = true;
      console.log(recordList.value, 'recordList.value');
    }
  } catch (e) {
    console.error('获取记录失败:', e);
    uni.showToast({ title: '获取记录列表失败', icon: 'none' });
  }
};

// 编辑记录
const editRecord = async () => {
  uni.navigateTo({
    url: `/pages/recordPages/addTurtle?type=edit&id=${theId.value}`,
  });
}

// 页面跳转
const toRecordDetail = (id) => {
  uni.navigateTo({ url: `/pages/recordPages/recordDetail?id=${id}` });
};

const toAddRecord = () => {
  uni.navigateTo({
    url: `/pages/recordPages/addRecord?id=${turtleMes.value._id}`,
  });
};

// 滑动操作处理
const clickItem = ({ data, index }) => {
  console.log(data, 'data');
  tabChoice(data, index);
};

const tabChoice = async (data, type) => {
  if (type === 0) {
    const confirm = await uni.showModal({
      title: `删除记录`,
      content: `您确定删除该条记录吗`,
      showCancel: true,
    });

    if (confirm.confirm) { // 修复确认逻辑，需要检查 confirm.confirm
      try {
        const res = await authRequest('removeOfRecord', { _id: data._id });
        
        if (res.result.code === 200) {
          const index = recordList.value.findIndex(
            (item) => item._id === data._id
          );
          recordList.value.splice(index, 1);
          uni.showToast({ title: '删除成功', icon: 'success' });
        }
      } catch (e) {
        console.error('删除失败:', e);
        uni.showToast({ title: '删除失败', icon: 'none' });
      }
    }
  } else if (type === 1) {
    const confirm = await uni.showModal({
      title: `置顶记录`,
      content: `您确定置顶该条记录吗`,
      showCancel: true,
    });
    // 置顶功能待实现
  }
};

const getTurtleYear = date => {
  const nowArr = (nowTime.value + '-01').split('-').map(Number)
  const dateArr = (date + '-01').split('-').map(Number)
  
  const y = Math.abs(nowArr[0] - dateArr[0])
  const m = nowArr[1] - dateArr[1]
  
  return `${y ? y + '年' : ''}${m ? Math.abs(m) + '个月' : ''}`
}

const close = (index) => {
  recordList.value[index].show = false;
};

// 生命周期
onLoad((option) => {
  theId.value = option.id;
  getTurtle();
});

onShow(() => {
  getTurtle();
  getRecordList();
});
</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  max-height: 100vh;
  min-height: 100vh;
  overflow-x: hidden;
  background: #eee;
  position: relative;

  .add_record {
    width: 100rpx;
    height: 100rpx;
    background: #3d836d;
    border-radius: 50%;
    position: fixed;
    bottom: 120rpx;
    right: 38rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 0 24rpx 12rpx rgba(202, 202, 202, 60%);
    .add_record_img {
      width: 90%;
      height: 90%;
    }
  }

  .detail_top {
    width: 100%;
    display: flex;
    padding: 38rpx 36rpx;
    box-shadow: 0 5px 5px -5px rgba(0, 0, 0, 0.5);
    // #ifdef H5
    margin-top: 82rpx;
    // #endif
    box-sizing: border-box;
    background: #3d836d;
    border-bottom-left-radius: 38rpx;
    border-bottom-right-radius: 38rpx;
    position: fixed;
    top: 0;
    z-index: 9998;
    .avatar {
      width: 180rpx;
      height: 180rpx;
      border-radius: 50%;
      background: #eee;
    }
    .top_right {
      padding-left: 36rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      color: #fff;
      .right_box {
        display: flex;
        align-items: center;
        .box_left {
          padding-right: 20rpx;
          font-size: 28rpx;
        }
        .box_right {
          font-size: 28rpx;
        }
      }
    }
  }

  .detail_content {
    width: 100%;
    padding: 0 22rpx 100rpx;
    box-sizing: border-box;
    .record_list {
      width: 100%;
      background: #fff;
      position: relative;
      padding-top: 250rpx;
      .record_item {
        padding: 32rpx 20rpx;
        box-sizing: border-box;
        border-bottom: 1rpx solid #ddd;
        position: relative;
        .data_title {
          font-size: 32rpx;
        }
        .data_tag {
          position: absolute;
          top: 10px;
          left: 10px;
          color: white;
          padding: 5px 10px;
          border-radius: 5px;
          font-size: 14px;
          font-weight: bold;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        .data_container {
          padding-left: 110rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          width: calc(100% - 110rpx);
        }
        .data_mes {
          text-align: right;
          font-size: 22rpx;
          padding-top: 20rpx;
          color: #999;
        }
      }
      .no_record {
        height: 300rpx;
        .record_item {
          padding-top: 100rpx;
          border-bottom: none;
          text-align: center;
          .data_title {
            font-size: 38rpx;
          }
        }
      }
    }

    .record_list:before {
      content: ' ';
      width: 0;
      height: 100%;
      position: absolute;
      /* 小球形状 */
      border-right: 18rpx dotted white;
      left: -6rpx;
      top: 0px;
    }
    // .record_list::after {
    //     content: ' ';
    //     width: 0;
    //     height: 100%;
    //     position: absolute;
    //     /* 小球形状 */
    //     border-right: 22rpx dotted white;
    //     right: -6rpx;
    //     top: 0px;
    // }
  }
}
</style>
